package com.example.myapplication.storage.database;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import com.example.myapplication.storage.entity.User;

import java.util.ArrayList;
import java.util.List;

/**
 * 演示通过SQLiteOpenHelper来操作SQLite数据库
 */
public class UserDBHelper extends SQLiteOpenHelper {

    public static final String DB_NAME = "user.db";
    public static final int DB_VERSION = 1;
    public static final String TABLE_NAME = "user_info";

    private static UserDBHelper instance;

    private SQLiteDatabase readableDatabase;
    private SQLiteDatabase writableDatabase;

    private UserDBHelper(Context context) {
        super(context, DB_NAME, null, DB_VERSION);
    }

    /**
     * 打开只读的数据库链接
     * @return 只读的数据库链接
     */
    public SQLiteDatabase openReadableConnection() {
        if (readableDatabase == null || !readableDatabase.isOpen()) {
            readableDatabase = instance.getReadableDatabase();
        }
        return readableDatabase;
    }

    /**
     * 打开读写的数据库链接
     * @return 读写的数据库链接
     */
    public SQLiteDatabase openWritableConnection() {
        if (writableDatabase == null || !writableDatabase.isOpen()) {
            writableDatabase = instance.getWritableDatabase();
        }
        return writableDatabase;
    }

    /**
     * 关闭数据库链接
     * @return
     */
    public void closeConnection() {
        if (readableDatabase != null && readableDatabase.isOpen()) {
            readableDatabase.close();
            readableDatabase = null;
        }
        if (writableDatabase != null && writableDatabase.isOpen()) {
            writableDatabase.close();
            writableDatabase = null;
        }
    }

    public static UserDBHelper getInstance(Context context) {
        // 客户端没有并发问题，不需要同步
        if (instance == null) {
            instance = new UserDBHelper(context);
        }
        return instance;
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // 执行建表脚本
        String sql = "create table if not exists user_info ( " +
                "_id integer primary key autoincrement not null," +
                "name varchar not null," +
                "age integer not null," +
                "height integer not null," +
                "weight float not null," +
                "married integer not null" +
                ");";
        db.execSQL(sql);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }

    public long insert(User user) {
        ContentValues values = new ContentValues();
        values.put("name", user.getName());
        values.put("age", user.getAge());
        values.put("height", user.getHeight());
        values.put("weight", user.getWeight());
        values.put("married", user.getMarried());
        return writableDatabase.insert(TABLE_NAME, null, values);
    }

    public long deleteByName(String name) {
        return writableDatabase.delete(TABLE_NAME, "name=?", new String[]{name});
    }

    public long updateByName(User user) {
        ContentValues values = new ContentValues();
        values.put("name", user.getName());
        if (user.getAge() != null) {
            values.put("age", user.getAge());
        }
        if (user.getHeight() != null) {
            values.put("height", user.getHeight());
        }
        if (user.getWeight() != null) {
            values.put("weight", user.getWeight());
        }
        if (user.getMarried() != null) {
            values.put("married", user.getMarried());
        }
        writableDatabase.beginTransaction();
        try {
            int affectedRows = writableDatabase.update(TABLE_NAME, values, "name=?", new String[]{user.getName()});
            writableDatabase.setTransactionSuccessful();
            return affectedRows;
        } finally {
            writableDatabase.endTransaction();
        }
    }

    public List<User> queryAll() {
        List<User> userList = new ArrayList<>();
        Cursor cursor = readableDatabase.query(
                TABLE_NAME, null, null, null, null, null, null);
        return decodeCursor(cursor);
    }

    public List<User> queryByName(String name) {
        List<User> userList = new ArrayList<>();
        Cursor cursor = readableDatabase.query(
                TABLE_NAME, null, "name=?", new String[]{name}, null, null, null);
        return decodeCursor(cursor);
    }

    private List<User> decodeCursor(Cursor cursor) {
        List<User> userList = new ArrayList<>();
        int idIndex = cursor.getColumnIndex("id");
        int nameIndex = cursor.getColumnIndex("name");
        int ageIndex = cursor.getColumnIndex("age");
        int heightIndex = cursor.getColumnIndex("height");
        int weightIndex = cursor.getColumnIndex("weight");
        int marriedIndex = cursor.getColumnIndex("married");
        while (cursor.moveToNext()) {
            User user = new User();
            if (idIndex != -1) {
                user.setId(cursor.getInt(0));
            }
            if (nameIndex != -1) {
                user.setName(cursor.getString(nameIndex));
            }
            if (ageIndex != -1) {
                user.setAge(cursor.getInt(ageIndex));
            }
            if (heightIndex != -1) {
                user.setHeight(cursor.getInt(heightIndex));
            }
            if (weightIndex != -1) {
                user.setWeight(cursor.getFloat(weightIndex));
            }
            if (marriedIndex != -1) {
                int marriedValue = cursor.getInt(marriedIndex);
                user.setMarried(marriedValue == 1);
            }
            userList.add(user);
        }
        return userList;
    }
}
